﻿using Ledict.ConditionExtract.IDAL;
using Ledict.ConditionExtract.Model;
using Ledict.Core.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Xml;
using Ledict.Utility.Extension;
using Ledict.ConditionExtract.Common;

namespace Ledict.ConditionExtract.DAL
{


    /// <summary>
    /// Tree数据操作
    /// </summary>
    public class SYS_InfoElementsDAL
    {
        private string DbName;
        private string Case;
        NewIDDAL nid = new NewIDDAL();
        public SYS_InfoElementsDAL()
        {
            DbName = "JudgeDoc";
            Case = "Caselibrary";
        }

        /// <summary>
        ///  获取要素中心节点树第一级节点和根据父级获取子节点
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public DataTable NodeTree_Tree(string pid)
        {
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetStoredProcCommand("sp_GetSYS_InfoElementsData");
            oBase.AddInParameter(oCmd, "@EICParentID", DbType.String, pid);
            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return OtB;
            }
            else
            {
                return new DataTable();
            }
        }

        /// <summary>
        /// 获取要素中心节点类型
        /// </summary>
        /// <param name="ccId"></param>
        /// <returns></returns>
        public DataTable GetInfoElementsType()
        {
            string strSql = " select AM_Code,AM_Name from SYS_Argument a join SYS_ArgumentType b on a.AT_ID=b.AT_ID where a.AT_ID='AT1807191548360002' order by a.AM_ShowIndex ";
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return OtB;
            }
            else
            {
                return new DataTable();
            }
        }

        /// <summary>
        /// 根据要素ID获取要素节点信息和要素xml结构
        /// </summary>
        public DataTable GetInfoElementsAndStructureByEICid(string EIC_ID)
        {
            string strSql = string.Format(@" select *from SYS_InfoElements a left join SYS_ElementStructure b on a.ES_ID=b.ES_ID where a.EIC_ID='{0}'  ", EIC_ID);
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return OtB;
            }
            else
            {
                return new DataTable();
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public SYS_InfoElements GetInfoElementsByEICid(string EIC_ID)
        {
            //StringBuilder strSql = new StringBuilder();
            //strSql.Append("select  top 1 * from dbo.SYS_InfoElements  ");
            //strSql.Append(" where EIC_ID=@EIC_ID ");
            string strSql = string.Format(@" select  top 1  a.*,b.ES_xml from SYS_InfoElements a left join SYS_ElementStructure b on a.ES_ID=b.ES_ID where a.EIC_ID='{0}' ", EIC_ID);
            SYS_InfoElements model = new SYS_InfoElements();
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());

            // oBase.AddInParameter(oCmd, "@EIC_ID", DbType.String, EIC_ID);
            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return DataRowToModel(OtB.Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 转换为对象实体
        /// </summary>
        public SYS_InfoElements DataRowToModel(DataRow row)
        {
            //EIC_ID, ES_ID, EIC_Name, EIC_Type, EIC_ParentID, EIC_XmlPath, EIC_AllParentID, EIC_level, EIC_SerialNumb
            SYS_InfoElements model = new SYS_InfoElements();
            if (row != null)
            {
                if (row["EIC_ID"] != null)
                {
                    model.EIC_ID = row["EIC_ID"].ToString();
                }
                if (row["ES_ID"] != null)
                {
                    model.ES_ID = row["ES_ID"].ToString();
                }
                if (row["EIC_Name"] != null)
                {
                    model.EIC_Name = row["EIC_Name"].ToString();
                }
                if (row["EIC_Type"] != null)
                {
                    model.EIC_Type = row["EIC_Type"].ToString();
                }
                if (row["EIC_ParentID"] != null)
                {
                    model.EIC_ParentID = row["EIC_ParentID"].ToString();
                }
                if (row["EIC_XmlPath"] != null)
                {
                    model.EIC_XmlPath = row["EIC_XmlPath"].ToString();
                }
                if (row["EIC_AllParentID"] != null && row["EIC_AllParentID"].ToString() != "")
                {
                    model.EIC_AllParentID = row["EIC_AllParentID"].ToString();
                }
                if (row["EIC_AllParentName"] != null && row["EIC_AllParentName"].ToString() != "")
                {
                    model.EIC_AllParentName = row["EIC_AllParentName"].ToString();
                }
                if (row["EIC_level"] != null && row["EIC_level"].ToString() != "")
                {
                    model.EIC_level = int.Parse(row["EIC_level"].ToString());
                }
                if (row["EIC_SerialNumb"] != null && row["EIC_SerialNumb"].ToString() != "")
                {
                    model.EIC_SerialNumb = decimal.Parse(row["EIC_SerialNumb"].ToString());
                }
                if (row["ES_xml"] != null && row["ES_xml"].ToString() != "")
                {
                    model.ES_xml = row["ES_xml"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        ///获取一个要素节点的父级的第一个流程性节点
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <returns></returns>
        public DataTable IsParentInfoElements(string EIC_ID)
        {
            //DataTable dt = new DataTable();                    
            //string[] strs = new string[0];
            ////DataTable dt = new DataTable();
            //Database db = DatabaseFactory.CreateDatabase(DbName);
            //string sql = string.Format(@" 	select EIC_AllParentID from SYS_InfoElements where EIC_ID='{0}' ", EIC_ID);
            //DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            //var obj = db.ExecuteScalar(oCmd);
            //if (obj != null)
            //{
            //    int index = obj.ToString().LastIndexOf(',');
            //    if (index != -1)
            //    {
            //        strs = obj.ToString().Remove(index).Split(',');
            //    }
            //    else
            //    {
            //        strs =new string[] { obj.ToString() };
            //    }
            //}
            //Database db1 = DatabaseFactory.CreateDatabase(DbName);
            //string sql1 = string.Format(@" select EIC_ID,EIC_Name from SYS_InfoElements where EIC_Type='t1' ");
            //DbCommand oCmd1 = db.GetSqlStringCommand(sql1.ToString());
            //var obj1 = db1.ExecuteDataSet(oCmd1);
            //if (obj1 != null && obj1.Tables[0] != null && obj1.Tables[0].Rows.Count > 0)
            //{
            //    dt = obj1.Tables[0];
            //}
            //if (strs.Length > 0 && dt.Rows.Count > 0)
            //{
            //    for (int i = strs.Length - 1; i >= 0; i--)
            //    {
            //        if (dt.Select("EIC_ID='" + strs[i] + "'").Length > 0)
            //        {

            DataTable dt = GetInfoElementsAndStructureByEICid("EIC1808141449580001");
            return dt;
            //            break;
            //        }
            //    }
            //}
            //return dt;
        }

        /// <summary>
        /// 根据EIC_ID判断该节点下是否有属性xml节点
        /// </summary>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public string IsHaveProperty(string EIC_ID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" select EIC_ID from SYS_InfoElements where EIC_ParentID='{0}' and EIC_Name='属性' ", EIC_ID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            var obj = db.ExecuteScalar(oCmd);
            if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
            {
                return obj.ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 添加属性后更改排序
        /// </summary>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public void AddPropertyUpdateSerialNum(string EIC_ID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" update SYS_InfoElements set EIC_SerialNumb=ISNULL(EIC_SerialNumb,0)+1 where EIC_ParentID='{0}' ", EIC_ID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            Int32 obj = db.ExecuteNonQuery(oCmd);
        }

        /// <summary>
        /// 添加要素节点
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public bool AddSYS_InfoElements(SYS_InfoElements Model, string username)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" INSERT INTO [Ldt_JudgeDocSystem].[dbo].[SYS_InfoElements]
           ([EIC_ID]
           ,[ES_ID]
           ,[EIC_Name]
           ,[EIC_Type]
           ,[EIC_ParentID]
           ,[EIC_XmlPath]
           ,[EIC_AllParentID]
           ,[EIC_level]
           ,[EIC_SerialNumb]
           ,[EIC_AllParentName])
     VALUES
           ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}') ", Model.EIC_ID, Model.ES_ID, Model.EIC_Name, Model.EIC_Type, Model.EIC_ParentID, Model.EIC_XmlPath, Model.EIC_AllParentID, Model.EIC_level, Model.EIC_SerialNumb, Model.EIC_AllParentName);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            Int32 obj = db.ExecuteNonQuery(oCmd);
            if (obj > 0)
            {
                OperLogDAL.AddOperLog(username, "insert", "SYS_InfoElements", "EIC_ID=" + Model.EIC_ID + "EIC_XmlPath" + Model.EIC_XmlPath);

                return true;
            }
            return false;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="Model"></param>
        /// <returns></returns>
        public bool UpdateSYS_InfoElements(SYS_InfoElements Model, string username)
        {
            string strSql = string.Format(@" UPDATE [Ldt_JudgeDocSystem].[dbo].[SYS_InfoElements]
   SET [ES_ID] = '{0}'
      ,[EIC_Name] = '{1}'
      ,[EIC_Type] ='{2}'
      ,[EIC_ParentID] = '{3}'
      ,[EIC_XmlPath] = '{4}'
      ,[EIC_AllParentID] ='{5}'
      ,[EIC_level] = '{6}'
      ,[EIC_SerialNumb] = '{7}'
      ,[EIC_AllParentName] ='{8}'
 WHERE EIC_ID='{9}' ", string.IsNullOrEmpty(Model.ES_ID) ? null : Model.ES_ID, string.IsNullOrEmpty(Model.EIC_Name) ? null : Model.EIC_Name, Model.EIC_Type, Model.EIC_ParentID, Model.EIC_XmlPath, Model.EIC_AllParentID, Model.EIC_level, Model.EIC_SerialNumb, Model.EIC_AllParentName, Model.EIC_ID);
            if (OperLogDAL.AddOperLog(username, "update", "SYS_InfoElements", "EIC_ID=" + Model.EIC_ID + " EIC_XmlPath：" + Model.EIC_XmlPath))
            {
                Database oBase = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
                if (oBase.ExecuteNonQuery(oCmd) > 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获取节点下面子节点的排序序号
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <returns></returns>
        public decimal GetNodeChildSerialNumber(string EIC_ID, bool NeedLast = false)
        {
            try
            {
                Database db = DatabaseFactory.CreateDatabase(DbName);
                string sql = string.Format(@" 	select MAX(EIC_SerialNumb) from SYS_InfoElements where EIC_ParentID='{0}' ", EIC_ID);
                DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
                string obj = db.ExecuteScalar(oCmd).ToString();
                if (NeedLast == true)
                {
                    return string.IsNullOrEmpty(obj) ? 1 : decimal.Parse(obj.ToString());
                }
                else
                {
                    return string.IsNullOrEmpty(obj) ? 1 : decimal.Parse(obj.ToString()) + 1;
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }

        /// <summary>
        /// 父节点下是否存在要素节点
        /// </summary>
        public string Exists(string EIC_Name, string EIC_ParentID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"	select EIC_ID from dbo.SYS_InfoElements
	       where EIC_Name=@EIC_Name
	       and EIC_ParentID=@EIC_ParentID ");
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
            oBase.AddInParameter(oCmd, "@EIC_Name", DbType.String, EIC_Name);
            oBase.AddInParameter(oCmd, "@EIC_ParentID", DbType.String, EIC_ParentID);
            return LdFormat.ObjectToString(oBase.ExecuteScalar(oCmd));
        }

        /// <summary>
        ///  插入要素XML
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <param name="sieModel"></param>
        /// <returns></returns>
        public bool InsertElementXML(string EIC_ID, SYS_ElementStructure sieModel)
        {
            string strSql = string.Format(@" 	insert into dbo.SYS_ElementStructure values('{0}','{1}','{2}','{3}','{4}') ", sieModel.ES_ID,sieModel.ES_Name,sieModel.ES_Type,sieModel.ES_xml,sieModel.ES_SerialNumb);
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
            if (oBase.ExecuteNonQuery(oCmd) > 0)
            {
                 strSql = string.Format(@" update SYS_InfoElements set ES_ID='{0}' where EIC_ID='{1}' ", sieModel.ES_ID,EIC_ID);
                Database oBase1 = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd1 = oBase.GetSqlStringCommand(strSql.ToString());
                oBase1.ExecuteNonQuery(oCmd1);
                return true;
            }
            return false;
        }

        /// <summary>
        ///  修改（XML）
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <param name="EI_ID"></param>
        /// <returns></returns>
        public bool UpdateElementXML(string EIC_ID, string ES_xml)
        {
            string strSql = string.Empty;
            SYS_InfoElements sie = GetInfoElementsByEICid(EIC_ID);
            if (!string.IsNullOrEmpty(sie.ES_ID))
            {
                strSql = string.Format(@" update dbo.SYS_ElementStructure set ES_xml='{0}' where ES_ID='{1}' ", ES_xml, sie.ES_ID);
                Database oBase = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
                if (oBase.ExecuteNonQuery(oCmd) > 0)
                {
                    return true;
                }
                return false;
            }
            else
            {
                return false;
            }                    
        }

        /// <summary>
        /// 删除要素节点(当前节点及节点下级)
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool DeleteSYS_InfoElements(string EIC_ID, string username)
        {
            string strSql = String.Format(@"delete  from dbo.SYS_InfoElements where charindex(',{0},', ',' + EIC_AllParentID + ',')>0 ", EIC_ID);
            if (OperLogDAL.AddOperLog(username, "delete", "SYS_InfoElements", "删除节点：" + EIC_ID))
            {
                Database oBase = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = oBase.GetSqlStringCommand(strSql);
                if (oBase.ExecuteNonQuery(oCmd) > 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 删除要素节点(节点下级)
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool DeleteSYS_InfoElements1(string EIC_ID, string username)
        {
            string strSql = String.Format(@"delete  from dbo.SYS_InfoElements where charindex(',{0},', ',' + EIC_AllParentID + ',')>0 and  EIC_ID<>'{0}' ", EIC_ID);
            if (OperLogDAL.AddOperLog(username, "delete", "SYS_InfoElements", "删除节点：" + EIC_ID))
            {
                Database oBase = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = oBase.GetSqlStringCommand(strSql);
                if (oBase.ExecuteNonQuery(oCmd) > 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 删除要素节点(当前节点)
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool DeleteSYS_InfoElementsByEICID(string EIC_ID, string username)
        {
            string strSql = String.Format(@"delete  from dbo.SYS_InfoElements where EIC_ID='{0}') ", EIC_ID);
            if (OperLogDAL.AddOperLog(username, "delete", "SYS_InfoElements", "删除节点：" + EIC_ID))
            {
                Database oBase = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = oBase.GetSqlStringCommand(strSql);
                if (oBase.ExecuteNonQuery(oCmd) > 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 根据节点名称或者节点ID模糊搜索
        /// </summary>
        /// <param name="FirPid"></param>
        /// <param name="name"></param>
        /// <param name="TreeNumber"></param>
        /// <returns></returns>
        public DataTable GetInfoElementSearch(string FirPid, string name)
        {
            string strSql = string.Format(@"  'select  row_number() over (order by  EIC_SerialNumb ) as showindex , EIC_ID  as id ,EIC_Name as name  from dbo.SYS_InfoElements where charindex('{0}', EIC_AllParentID) > 0 and(EIC_Name like'' % '{1}' % '' or EIC_ID = '{1}')'  ", FirPid, name);
            Database oBase = DatabaseFactory.CreateDatabase(DbName);
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());
            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return OtB;
            }
            else
            {
                return new DataTable();
            }
        }


        /// <summary>
        /// 根据EIC_ID获取该节点下是否配置了来源规则
        /// </summary>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public bool GetExpressSourceByEIC_ID(string EIC_ID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" select COUNT(1) from SYS_InfoElements  where CHARINDEX(',{0},',','+EIC_AllParentID+',')>0 and EIC_ID in(select distinct CC_ID from SYS_Express_Source) ", EIC_ID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            var obj = db.ExecuteScalar(oCmd);
            if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
            {
                return Convert.ToInt32(obj) > 0 ? true : false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据节点获取节点下面的节点类型
        /// </summary>
        /// <param name="CC_ID"></param>
        /// <returns></returns>
        public List<SYS_InfoElementsType> GetInfoElementsTypeByEICId(string CC_ID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" 	  select AM_Code,AM_Name from SYS_Argument where AT_ID='AT1807191548360002' and AM_Code in( select distinct EIC_Type from SYS_InfoElements  where CHARINDEX(',{0},',','+EIC_AllParentID+',')>0 ) ", CC_ID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            var dt = db.ExecuteDataSet(oCmd).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                var list = new List<SYS_InfoElementsType>();
                foreach (DataRow dr in dt.Rows)
                {
                    var obj = new SYS_InfoElementsType { AM_Code = dr["AM_Code"].ToString(), AM_Name = dr["AM_Name"].ToString() };
                    list.Add(obj);
                }
                return list;
            }
            return null;
        }


        /// <summary>
        ///判断目标节点是否是原节点的子集 
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <returns></returns>
        public bool IsParentRealation(string source_ID, string target_ID)
        {
            string[] strs = new string[0];
            SYS_InfoElements sie = GetInfoElementsByEICid(target_ID);
            if (!string.IsNullOrEmpty(sie.EIC_AllParentID))
            {
                int index = sie.EIC_AllParentID.ToString().LastIndexOf(',');
                if (index != -1)
                {
                    strs = sie.EIC_AllParentID.ToString().Remove(index).Split(',');
                    foreach (var str in strs)
                    {
                        if (str == source_ID)
                        {
                            return true;
                        }
                    }
                }
            }
            else
            {
                return false;
            }
            return false;
        }

        /// <summary>
        /// 根据CCID获取下级节点名称
        /// </summary>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public List<string> GetTongJiNodes(string ccID)
        {
            List<string> obj = new List<string>();
            DataTable table = NodeTree_Tree(ccID);
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataRow item in table.Rows)
                {
                    obj.Add(Convert.ToString(item["name"]));
                }
            }
            return obj;
        }


        /// <summary>
        ///获取一个节点的父级的第一个案由节点
        /// </summary>
        /// <param name="EIC_ID"></param>
        /// <returns></returns>
        public SYS_InfoElements IsParentRealation1(string ccID)
        {
            SYS_InfoElements objCaseCause = new SYS_InfoElements();
            string[] strs = new string[0];
            DataTable dt = new DataTable();
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" 	select EIC_AllParentID from SYS_InfoElements where EIC_ID='{0}' ", ccID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            var obj = db.ExecuteScalar(oCmd);
            if (obj != null)
            {
                int index = obj.ToString().LastIndexOf(',');
                if (index != -1)
                {
                    strs = obj.ToString().Remove(index).Split(',');
                }
            }


            Database db1 = DatabaseFactory.CreateDatabase(DbName);
            string sql1 = string.Format(@" select EIC_ID,EIC_Name from SYS_InfoElements where EIC_Type=1 ");
            DbCommand oCmd1 = db.GetSqlStringCommand(sql1.ToString());
            var obj1 = db1.ExecuteDataSet(oCmd1);
            if (obj1 != null && obj1.Tables[0] != null && obj1.Tables[0].Rows.Count > 0)
            {
                dt = obj1.Tables[0];
            }
            if (strs.Length > 0 && dt.Rows.Count > 0)
            {
                for (int i = strs.Length - 1; i >= 0; i--)
                {
                    if (dt.Select("EIC_ID='" + strs[i] + "'").Length > 0)
                    {

                        objCaseCause = GetInfoElementsByEICid(strs[i].ToString());
                        break;
                    }
                }
            }
            return objCaseCause;
        }


        /// <summary>
        /// 更改节点排序
        /// </summary>
        /// <param name="sourceItemId"></param>
        /// <param name="targetItemId"></param>
        /// <returns></returns>
        public bool UpdateItemSort(SYS_InfoElements sourceItem, SYS_InfoElements targetItem, string moveState)
        {
            decimal sourceSort = sourceItem.EIC_SerialNumb;
            decimal targetSort = targetItem.EIC_SerialNumb;
            string sql = "";
            //来源节点XML
            DataTable caseCausexml = GetInfoElementsAndStructureByEICid(sourceItem.EIC_ID);
            // SYS_InfoElements caseCausexml = IsParentRealation1(sourceItem.EIC_ID);
            //目标节点xml
            DataTable caseTargetCausexml = GetInfoElementsAndStructureByEICid(targetItem.EIC_ID);
            //  SYS_InfoElements caseTargetCausexml = IsParentRealation1(targetItem.EIC_ID);
            //同一个父节点下的节点
            if (sourceItem.EIC_ParentID == targetItem.EIC_ParentID)
            {
                if (moveState == "上方" && sourceSort < targetSort)
                {
                    //修改节点移动后需要排序的节点
                    sql = string.Format(@" update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb-1 
                                    where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2}  ",
                                    sourceItem.EIC_ParentID, sourceSort + 1, targetSort - 1);
                    //修改目标节点
                    sql = string.Format(@"{0};update SYS_InfoElements set EIC_SerialNumb = {1}
                                      where EIC_ID='{2}'",
                                   sql, targetItem.EIC_SerialNumb - 1, sourceItem.EIC_ID);
                }
                else if (moveState == "上方" && sourceSort > targetSort)
                {
                    sql = string.Format(@"update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb+1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2}",
                                      sourceItem.EIC_ParentID, targetSort, sourceSort - 1);
                    //修改目标节点
                    sql = string.Format(@"{0};update SYS_InfoElements set EIC_SerialNumb = {1}
                                      where EIC_ID='{2}'",
                                   sql, targetItem.EIC_SerialNumb, sourceItem.EIC_ID);
                }
                else if (moveState == "下方" && sourceSort < targetSort)
                {
                    sql = string.Format(@"update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb-1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2}",
                                      sourceItem.EIC_ParentID, sourceSort + 1, targetSort);
                    //修改目标节点
                    sql = string.Format(@"{0};update SYS_InfoElements set EIC_SerialNumb = {1}
                                      where EIC_ID='{2}'",
                                   sql, targetItem.EIC_SerialNumb, sourceItem.EIC_ID);
                }
                else if (moveState == "下方" && sourceSort > targetSort)
                {
                    sql = string.Format(@"update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb+1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2}",
                                      sourceItem.EIC_ParentID, targetSort + 1, sourceSort - 1);
                    //修改目标节点
                    sql = string.Format(@"{0};update SYS_InfoElements set EIC_SerialNumb = {1}
                                      where EIC_ID='{2}'",
                                   sql, targetItem.EIC_SerialNumb + 1, sourceItem.EIC_ID);
                }
            }
            else
            {
                //获取当前节点的最后一个排号节点
                decimal SourceccSerialNumber = GetNodeChildSerialNumber(sourceItem.EIC_ParentID, true);
                decimal targetccSerialNumber = GetNodeChildSerialNumber(targetItem.EIC_ParentID, true);
                if (moveState == "上方")
                {
                    //目标节点排号排序
                    sql = string.Format(@"update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb+1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2};",
                                      targetItem.EIC_ParentID, targetItem.EIC_SerialNumb, targetccSerialNumber);
                    DataTable dt = NodeTree_Tree(sourceItem.EIC_ParentID);
                    if (dt != null && dt.Rows.Count > 1)
                    {
                        //原节点排号排序
                        sql += string.Format(@"  update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb-1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2};",
                                    sourceItem.EIC_ParentID, sourceItem.EIC_SerialNumb + 1, SourceccSerialNumber);
                    }
                    string EIC_AllParentID = targetItem.EIC_AllParentID.Replace(targetItem.EIC_ID, "") + sourceItem.EIC_ID;
                    string EIC_AllParentName = targetItem.EIC_AllParentName.Replace(targetItem.EIC_Name, "") + sourceItem.EIC_Name;
                    //修改目标节点
                    sql += string.Format(@" update SYS_InfoElements set EIC_SerialNumb = {0},EIC_ParentID='{1}' where EIC_ID='{2}';",
                                    targetItem.EIC_SerialNumb, targetItem.EIC_ParentID, sourceItem.EIC_ID);

                    //原节点全部父级ID
                    string sourceAllParentId = sourceItem.EIC_AllParentID;
                    //目标节点全部父级ID
                    string targetAllParentId = targetItem.EIC_AllParentID.Replace("," + targetItem.EIC_ID, "") + "," + sourceItem.EIC_ID;

                    //原节点全部父级路径
                    string sourceAllParentName = sourceItem.EIC_AllParentName;
                    //目标节点全部父级路径
                    string targetAllParentName = targetItem.EIC_AllParentName.Replace("," + targetItem.EIC_Name, "") + "," + sourceItem.EIC_Name;

                    //原节点EIC_XmlPath
                    string sourceXmlPath = sourceItem.EIC_XmlPath;

                    //目标节点EIC_XmlPath
                    string targetXmlPath = targetItem.EIC_XmlPath.Replace("/" + targetItem.EIC_Name, "") + (sourceItem.EIC_Name == "属性" ? "" : "/" + sourceItem.EIC_Name);


                    int i = targetAllParentId.Split(',').Length;

                    sql += string.Format(@" update SYS_InfoElements set EIC_level='{0}'  where EIC_AllParentName like '{1}%' ;", i, sourceAllParentName);

                    sql += string.Format(@" update SYS_InfoElements set EIC_AllParentID=REPLACE(EIC_AllParentID,'{0}','{1}')  where EIC_AllParentID like '{0}%' ;", sourceAllParentId, targetAllParentId);

                    sql += string.Format(@" update SYS_InfoElements set EIC_AllParentName=REPLACE(EIC_AllParentName,'{0}','{1}')  where EIC_AllParentName like '{0}%' ;", sourceAllParentName, targetAllParentName);

                    sql += string.Format(@" update SYS_InfoElements set EIC_XmlPath=REPLACE(EIC_XmlPath,'{0}','{1}')  where EIC_XmlPath like '{0}%' and CHARINDEX('{2}',EIC_AllParentID)>0 ;", sourceXmlPath, targetXmlPath, sourceItem.EIC_ID);

                }
                else if (moveState == "下方")
                {
                    sql = string.Format(@"update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb+1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2};",
                                      targetItem.EIC_ParentID, targetItem.EIC_SerialNumb + 1, targetccSerialNumber);
                    DataTable dt = NodeTree_Tree(sourceItem.EIC_ParentID);
                    if (dt != null && dt.Rows.Count > 1)
                    {
                        //原节点排号排序
                        sql += string.Format(@"  update SYS_InfoElements set EIC_SerialNumb = EIC_SerialNumb-1
                                      where EIC_ParentID='{0}' and EIC_SerialNumb between {1} and {2};",
                                        sourceItem.EIC_ParentID, sourceItem.EIC_SerialNumb + 1, SourceccSerialNumber);
                    }
                    string EIC_AllParentID = targetItem.EIC_AllParentID.Replace(targetItem.EIC_ID, "") + sourceItem.EIC_ID;
                    string EIC_AllParentName = targetItem.EIC_AllParentName.Replace(targetItem.EIC_Name, "") + sourceItem.EIC_Name;
                    //修改目标节点
                    sql += string.Format(@" update SYS_InfoElements set EIC_SerialNumb = {0},EIC_ParentID='{1}' where EIC_ID='{2}';",
                                    targetItem.EIC_SerialNumb + 1, targetItem.EIC_ParentID, sourceItem.EIC_ID);

                    //原节点全部父级ID
                    string sourceAllParentId = sourceItem.EIC_AllParentID;
                    //目标节点全部父级ID
                    string targetAllParentId = targetItem.EIC_AllParentID.Replace("," + targetItem.EIC_ID, "") + "," + sourceItem.EIC_ID;

                    //原节点全部父级路径
                    string sourceAllParentName = sourceItem.EIC_AllParentName;
                    //目标节点全部父级路径
                    string targetAllParentName = targetItem.EIC_AllParentName.Replace("," + targetItem.EIC_Name, "") + "," + sourceItem.EIC_Name;

                    //原节点EIC_XmlPath
                    string sourceXmlPath = sourceItem.EIC_XmlPath;

                    //目标节点EIC_XmlPath
                    string targetXmlPath = targetItem.EIC_XmlPath.Replace("/" + targetItem.EIC_Name, "") + (sourceItem.EIC_Name == "属性" ? "" : "/" + sourceItem.EIC_Name);


                    int i = targetAllParentId.Split(',').Length;

                    sql += string.Format(@" update SYS_InfoElements set EIC_level='{0}'  where EIC_AllParentName like '{1}%' ;", i, sourceAllParentName);

                    sql += string.Format(@" update SYS_InfoElements set EIC_AllParentID=REPLACE(EIC_AllParentID,'{0}','{1}')  where EIC_AllParentID like '{0}%' ;", sourceAllParentId, targetAllParentId);

                    sql += string.Format(@" update SYS_InfoElements set EIC_AllParentName=REPLACE(EIC_AllParentName,'{0}','{1}')  where EIC_AllParentName like '{0}%' ;", sourceAllParentName, targetAllParentName);

                    sql += string.Format(@" update SYS_InfoElements set EIC_XmlPath=REPLACE(EIC_XmlPath,'{0}','{1}')  where EIC_XmlPath like '{0}%'  and CHARINDEX('{2}',EIC_AllParentID)>0  ;", sourceXmlPath, targetXmlPath, sourceItem.EIC_ID);

                }
            }
            if (moveState == "下级")
            {
                //原节点全部父级ID
                string sourceAllParentId = sourceItem.EIC_AllParentID;
                //目标节点全部父级ID
                string targetAllParentId = targetItem.EIC_AllParentID + "," + sourceItem.EIC_ID;

                //原节点全部父级路径
                string sourceAllParentName = sourceItem.EIC_AllParentName;
                //目标节点全部父级路径
                string targetAllParentName = targetItem.EIC_AllParentName + "," + sourceItem.EIC_Name;

                //原节点EIC_XmlPath
                string sourceXmlPath = sourceItem.EIC_XmlPath;

                //目标节点EIC_XmlPath
                string targetXmlPath = targetItem.EIC_XmlPath + (sourceItem.EIC_Name == "属性" ? "" : "/" + sourceItem.EIC_Name);

                int i = targetAllParentId.Split(',').Length;

                sql += string.Format(@" update SYS_InfoElements set EIC_level='{0}'  where EIC_AllParentName like '{1}%' ;", i, sourceAllParentName);

                sql += string.Format(@" update SYS_InfoElements set EIC_AllParentID=REPLACE(EIC_AllParentID,'{0}','{1}')  where EIC_AllParentID like '{0}%' ;", sourceAllParentId, targetAllParentId);

                sql += string.Format(@" update SYS_InfoElements set EIC_AllParentName=REPLACE(EIC_AllParentName,'{0}','{1}')  where EIC_AllParentName like '{0}%' ;", sourceAllParentName, targetAllParentName);

                sql += string.Format(@" update SYS_InfoElements set EIC_XmlPath=REPLACE(EIC_XmlPath,'{0}','{1}')  where EIC_XmlPath like '{0}%'  and CHARINDEX('{2}',EIC_AllParentID)>0 ;", sourceXmlPath, targetXmlPath, sourceItem.EIC_ID);

                decimal ccSerialNumber = GetNodeChildSerialNumber(targetItem.EIC_ID);
                sql += string.Format(@" update  SYS_InfoElements set EIC_SerialNumb ='{0}', EIC_ParentID='{1}' where EIC_ID='{2}' ;", ccSerialNumber, targetItem.EIC_ID, sourceItem.EIC_ID);

                //最后一个节点的排号
                decimal lastSerialNumber = GetNodeChildSerialNumber(sourceItem.EIC_ParentID, true);
                sql += string.Format(@" update SYS_InfoElements set EIC_SerialNumb =EIC_SerialNumb-1 where EIC_SerialNumb between {0} and {1} and  EIC_ParentID='{2}' ;", sourceSort + 1, lastSerialNumber, sourceItem.EIC_ParentID);



                #region MyRegion
                ////获取来源节点下面的子节点集合
                //DataTable dt = treedal.NodeTree_Tree(sourceItem.EIC_ID);
                //if (dt != null && dt.Rows.Count > 0)
                //{
                //    for (int i = 0; i < dt.Rows.Count; i++)
                //    {
                //        SYS_CaseCause obj = GetCaseCauseByCcid(dt.Rows[i]["id"].ToString());
                //        string nodeStr = obj.EIC_AllParentID;
                //        int index = nodeStr.IndexOf("," + sourceItem.EIC_ID);
                //        string resAllParentId = nodeStr.Insert(index, "," + targetItem.EIC_ID);
                //        nodeStr = obj.EIC_AllParentName;
                //        index = nodeStr.IndexOf("," + sourceItem.EIC_Name);
                //        string resAllParentName = nodeStr.Insert(index, "," + targetItem.EIC_Name);
                //        sql += string.Format(@" update  SYS_CaseCause set EIC_AllParentID='{0}',EIC_AllParentName='{1}' where EIC_ID='{2}'  ", resAllParentId, resAllParentName, obj.EIC_ID);

                //    }
                //    //原节点全部父级ID
                //    string sourceAllParentId = sourceItem.EIC_AllParentID;
                //    //目标节点全部父级ID
                //    string targetAllParentId = targetItem.EIC_AllParentID + "," + sourceItem.EIC_ID;

                //    //原节点全部父级路径
                //    string sourceAllParentName = sourceItem.EIC_AllParentName;
                //    //目标节点全部父级路径
                //    string targetAllParentName = targetItem.EIC_AllParentName + "," + sourceItem.EIC_Name;

                //    sql += string.Format(@" update SYS_CaseCause set EIC_AllParentID=REPLACE(EIC_AllParentID,'{0}','{1}')  where EIC_AllParentID like '{0}%' ",sourceAllParentId,targetAllParentId);

                //    sql += string.Format(@" update SYS_CaseCause set EIC_AllParentName=REPLACE(EIC_AllParentName,'{0}','{1}')  where EIC_AllParentName like '{0}%' ", sourceAllParentName, targetAllParentName);

                //    double ccSerialNumber = GetNodeChildSerialNumber(targetItem.EIC_ID);
                //    sql += string.Format(@" update  SYS_CaseCause set EIC_SerialNumb ='{0}', EIC_ParentID='{1}' where EIC_ID='{2}' ", ccSerialNumber, targetItem.EIC_ID, sourceItem.EIC_ID);

                //    //最后一个节点的排号
                //    double lastSerialNumber = GetNodeChildSerialNumber(sourceItem.EIC_ParentID, true);
                //    sql += string.Format(@" update SYS_CaseCause set EIC_SerialNumb =EIC_SerialNumb-1 where EIC_SerialNumb between {0} and {1} and  EIC_ParentID='{2}' ", sourceSort + 1, lastSerialNumber, sourceItem.EIC_ParentID);


                //}
                //else //没有子节点
                //{
                //    string str = sourceItem.EIC_AllParentID;
                //    int index = str.IndexOf("," + sourceItem.EIC_ID);
                //    string resAllParentId = str.Insert(index, "," + targetItem.EIC_ID);
                //    str = sourceItem.EIC_AllParentName;
                //    index = str.IndexOf("," + sourceItem.EIC_Name);
                //    string resAllParentName = str.Insert(index, "," + targetItem.EIC_Name);
                //    double ccSerialNumber = GetNodeChildSerialNumber(targetItem.EIC_ID);
                //    sql = string.Format(@" update  SYS_CaseCause set EIC_SerialNumb ='{0}',
                //                               EIC_ParentID='{1}',EIC_AllParentID='{2}',EIC_AllParentName='{3}' where EIC_ID='{4}' ;", ccSerialNumber, targetItem.EIC_ID, resAllParentId, resAllParentName, sourceItem.EIC_ID);
                //}
                ////最后一个节点的排号
                //double lastSerialNumber = GetNodeChildSerialNumber(sourceItem.EIC_ParentID, true);
                //sql += string.Format(@" update SYS_CaseCause set EIC_SerialNumb =EIC_SerialNumb-1 where EIC_SerialNumb between {0} and {1} and  EIC_ParentID='{2}' ", sourceSort + 1, lastSerialNumber, sourceItem.EIC_ParentID); 
                #endregion
            }

            int result = 0;
            if (!string.IsNullOrEmpty(sql.ToString()))
            {
                Database db = DatabaseFactory.CreateDatabase(DbName);
                DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
                result = db.ExecuteNonQuery(oCmd);

            }

            //节点移动
            if ((!string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString()) || !string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString())) && sourceItem.EIC_Type == "t2" && targetItem.EIC_Type == "t2")
            {
                XmlDocument doc = new XmlDocument();
                XmlDocument doc1 = new XmlDocument();
                XmlNode objxml = null;
                XmlNode objParentXml = null;
                XmlNode objxml1 = null;
                XmlNode objParentXml1 = null;
                if (!string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString()))
                {
                    string xml = caseCausexml.Rows[0]["ES_xml"].ToString().Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                    doc.LoadXml(xml);

                    int i = sourceItem.EIC_AllParentName.LastIndexOf(caseCausexml.Rows[0]["EIC_Name"].ToString());
                    string EIC_XmlPath = sourceItem.EIC_AllParentName.Substring(i);
                    string[] strs = EIC_XmlPath.Split(',');
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in strs)
                    {
                        sb.Append("/" + item);
                    }
                    //原节点路由
                    string res1 = sb.ToString();
                    if (!string.IsNullOrEmpty(res1))
                    {
                        objxml = doc.SelectSingleNode(res1);
                        if (objxml != null)
                        {
                            objParentXml = objxml.ParentNode;
                        }
                    }
                }
                bool b = false;
                if (!string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString()))
                {
                    if (caseCausexml.Rows[0]["EIC_ID"].ToString() == caseTargetCausexml.Rows[0]["EIC_ID"].ToString())
                    {
                        doc1 = doc;
                        b = true;
                    }
                    else
                    {
                        string xml = caseTargetCausexml.Rows[0]["ES_xml"].ToString().Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                        doc1.LoadXml(xml);
                    }

                    int i = targetItem.EIC_AllParentName.LastIndexOf(caseTargetCausexml.Rows[0]["EIC_Name"].ToString());
                    string EIC_XmlPath = targetItem.EIC_AllParentName.Substring(i);
                    string[] strs = EIC_XmlPath.Split(',');
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in strs)
                    {
                        sb.Append("/" + item);
                    }
                    //目标节点路由
                    string res2 = sb.ToString();
                    if (!string.IsNullOrEmpty(res2))
                    {
                        objxml1 = doc1.SelectSingleNode(res2);
                        if (objxml1 != null)
                        {
                            objParentXml1 = objxml1.ParentNode;
                        }
                    }
                }

                //XmlElement objxml001 = (XmlElement)objxml1;
                //XmlAttribute objxml01 = objxml001.GetAttributeNode(objxml.Attributes[0].Name);

                //XmlNode objParenetXml = objxml.ParentNode;          
                //XmlAttributeCollection objcola1 = objxml.Attributes;
                //XmlAttributeCollection objcola2 = objxml1.Attributes;
                if (moveState == "上方")
                {
                    if (objParentXml != null)
                    {
                        objParentXml.RemoveChild(objxml);
                    }
                    if (objParentXml1 != null && objxml != null && objxml1 != null)
                    {
                        objParentXml1.InsertBefore(doc1.ImportNode(objxml, true), objxml1);
                    }
                    else if (objParentXml1 != null && objxml1 != null)
                    {
                        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                        objParentXml1.AppendChild(objElement);
                        // objParentXml1.AppendChild(doc1.ImportNode(objElement,true));
                    }
                }
                else if (moveState == "下方")
                {
                    if (objParentXml != null)
                    {
                        objParentXml.RemoveChild(objxml);
                    }
                    if (objParentXml1 != null && objxml != null && objxml1 != null)
                    {
                        objParentXml1.InsertAfter(doc1.ImportNode(objxml, true), objxml1);
                    }
                    else if (objParentXml1 != null && objxml1 != null)
                    {
                        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                        objParentXml1.AppendChild(objElement);
                        // objParentXml1.AppendChild(doc1.ImportNode(objElement,true));
                    }
                }
                else if (moveState == "下级")
                {
                    if (objParentXml != null)
                    {
                        objParentXml.RemoveChild(objxml);
                    }
                    if (objParentXml1 != null && objxml != null && objxml1 != null)
                    {
                        objxml1.AppendChild(objxml);
                    }
                    else if (objParentXml1 != null && objxml1 != null)
                    {
                        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                        objParentXml1.AppendChild(objElement);
                        // objxml1.AppendChild(doc1.ImportNode(objElement, true));
                    }
                }
                if (b)
                {
                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                    {
                        string res3 = FormatXML(doc1.InnerXml.ToString());
                        bool res = UpdateElementXML(caseCausexml.Rows[0]["EIC_ID"].ToString(), res3);
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                    {
                        string res3 = FormatXML(doc.InnerXml.ToString());
                        bool res = UpdateElementXML(caseCausexml.Rows[0]["EIC_ID"].ToString(), res3);
                    }

                    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                    {
                        string res3 = FormatXML(doc1.InnerXml.ToString());
                        bool res = UpdateElementXML(caseTargetCausexml.Rows[0]["EIC_ID"].ToString(), res3);
                    }
                }
            }
            else if (!string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString()) && sourceItem.EIC_Type == "t3" && targetItem.EIC_Type == "t3" && sourceItem.EIC_ParentID == targetItem.EIC_ParentID)
            {
                XmlDocument doc = new XmlDocument();
                XmlNode objxml = null;
                string xml = caseCausexml.Rows[0]["ES_xml"].ToString().Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                doc.LoadXml(xml);

                int i = sourceItem.EIC_AllParentName.LastIndexOf(caseCausexml.Rows[0]["EIC_Name"].ToString());
                string EIC_XmlPath = sourceItem.EIC_AllParentName.Substring(i);
                int j = EIC_XmlPath.LastIndexOf(",属性");
                EIC_XmlPath = EIC_XmlPath.Substring(0, j);
                string[] strs = EIC_XmlPath.Split(',');
                StringBuilder sb = new StringBuilder();
                foreach (var item in strs)
                {
                    sb.Append("/" + item);
                }
                //原节点路由
                string res1 = sb.ToString();
                if (!string.IsNullOrEmpty(res1))
                {
                    XmlElement obj = null;
                    objxml = doc.SelectSingleNode(res1);
                    if (objxml != null)
                    {
                        obj = (XmlElement)objxml;
                        obj.RemoveAllAttributes();
                    }
                    DataTable dt = GetAttributesByCCID(sourceItem.EIC_ParentID);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in dt.Rows)
                        {
                            string ss = item["EIC_Name"].ToString();
                            obj.SetAttribute(item[0].ToString(), "");
                        }
                    }
                    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                    {
                        string res3 = FormatXML(doc.InnerXml.ToString());
                        bool res = UpdateElementXML(caseCausexml.Rows[0]["EIC_ID"].ToString(), res3);
                    }
                }
            }
            else if ((!string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString()) || !string.IsNullOrEmpty(caseCausexml.Rows[0]["ES_xml"].ToString())) && (sourceItem.EIC_Type == "t2" || sourceItem.EIC_Type == "t3"))
            {
                #region 原注释代码
                //XmlDocument doc = new XmlDocument();
                //XmlDocument doc1 = new XmlDocument();
                //XmlNode objxml = null;
                //XmlNode objParentXml = null;
                //XmlNode objxml1 = null;
                //XmlNode objParentXml1 = null;
                //if (!string.IsNullOrEmpty(caseCausexml.ES_xml))
                //{
                //    string xml = caseCausexml.ES_xml.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                //    doc.LoadXml(xml);

                //    int i = sourceItem.EIC_AllParentName.LastIndexOf(caseCausexml.EIC_Name);
                //    string EIC_XmlPath = sourceItem.EIC_AllParentName.Substring(i);
                //    string[] strs = EIC_XmlPath.Split(',');
                //    StringBuilder sb = new StringBuilder();
                //    foreach (var item in strs)
                //    {
                //        sb.Append("/" + item);
                //    }
                //    //原节点路由
                //    string res1 = sb.ToString();
                //    if (!string.IsNullOrEmpty(res1))
                //    {
                //        objxml = doc.SelectSingleNode(res1);
                //        if (objxml != null)
                //        {
                //            objParentXml = objxml.ParentNode;
                //        }
                //    }
                //}
                //bool b = false;
                //if (!string.IsNullOrEmpty(caseTargetCausexml.ES_xml))
                //{
                //    if (caseCausexml.EIC_ID == caseTargetCausexml.EIC_ID)
                //    {
                //        doc1 = doc;
                //        b = true;
                //    }
                //    else
                //    {
                //        string xml = caseTargetCausexml.ES_xml.Replace("\r", "").Replace("\t", "").Replace("\n", "").Replace("-", "").Replace("、", @"");
                //        doc1.LoadXml(xml);
                //    }

                //    int i = targetItem.EIC_AllParentName.LastIndexOf(caseTargetCausexml.EIC_Name);
                //    string EIC_XmlPath = targetItem.EIC_AllParentName.Substring(i);
                //    string[] strs = EIC_XmlPath.Split(',');
                //    StringBuilder sb = new StringBuilder();
                //    foreach (var item in strs)
                //    {
                //        sb.Append("/" + item);
                //    }
                //    //目标节点路由
                //    string res2 = sb.ToString();
                //    if (!string.IsNullOrEmpty(res2))
                //    {
                //        objxml1 = doc1.SelectSingleNode(res2);
                //        if (objxml1 != null)
                //        {
                //            objParentXml1 = objxml1.ParentNode;
                //        }
                //    }
                //}

                ////XmlElement objxml001 = (XmlElement)objxml1;
                ////XmlAttribute objxml01 = objxml001.GetAttributeNode(objxml.Attributes[0].Name);

                ////XmlNode objParenetXml = objxml.ParentNode;          
                ////XmlAttributeCollection objcola1 = objxml.Attributes;
                ////XmlAttributeCollection objcola2 = objxml1.Attributes;
                //if (moveState == "上方")
                //{
                //    if (objParentXml != null)
                //    {
                //        objParentXml.RemoveChild(objxml);
                //    }
                //    if (objParentXml1 != null && objxml != null && objxml1 != null)
                //    {
                //        objParentXml1.InsertBefore(doc1.ImportNode(objxml, true), objxml1);
                //    }
                //    else if (objParentXml1 != null && objxml1 != null)
                //    {
                //        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                //        objParentXml1.AppendChild(objElement);
                //        // objParentXml1.AppendChild(doc1.ImportNode(objElement,true));
                //    }
                //}
                //else if (moveState == "下方")
                //{
                //    if (objParentXml != null)
                //    {
                //        objParentXml.RemoveChild(objxml);
                //    }
                //    if (objParentXml1 != null && objxml != null && objxml1 != null)
                //    {
                //        objParentXml1.InsertAfter(doc1.ImportNode(objxml, true), objxml1);
                //    }
                //    else if (objParentXml1 != null && objxml1 != null)
                //    {
                //        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                //        objParentXml1.AppendChild(objElement);
                //        // objParentXml1.AppendChild(doc1.ImportNode(objElement,true));
                //    }
                //}
                //else if (moveState == "下级")
                //{
                //    if (objParentXml != null)
                //    {
                //        objParentXml.RemoveChild(objxml);
                //    }
                //    if (objParentXml1 != null && objxml != null && objxml1 != null)
                //    {
                //        objxml1.AppendChild(objxml);
                //    }
                //    else if (objParentXml1 != null && objxml1 != null)
                //    {
                //        XmlElement objElement = doc1.CreateElement(sourceItem.EIC_Name);
                //        objParentXml1.AppendChild(objElement);
                //        // objxml1.AppendChild(doc1.ImportNode(objElement, true));
                //    }
                //}
                //if (b)
                //{
                //    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                //    {
                //        string res3 = FormatXML(doc1.InnerXml.ToString());
                //        bool res = UpdateElementXML(caseCausexml.EIC_ID, res3);
                //    }
                //}
                //else
                //{
                //    if (!string.IsNullOrEmpty(doc.InnerXml.ToString()))
                //    {
                //        string res3 = FormatXML(doc.InnerXml.ToString());
                //        bool res = UpdateElementXML(caseCausexml.EIC_ID, res3);
                //    }

                //    if (!string.IsNullOrEmpty(doc1.InnerXml.ToString()))
                //    {
                //        string res3 = FormatXML(doc1.InnerXml.ToString());
                //        bool res = UpdateElementXML(caseTargetCausexml.EIC_ID, res3);
                //    }
                //} 
                #endregion
            }
            return result > 0 ? true : false;
        }

        /// <summary>
        /// 根据ccid获取该节点下面的属性
        /// </summary>
        /// <param name="ccID"></param>
        /// <returns></returns>
        public DataTable GetAttributesByCCID(string ccID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" 	select EIC_Name from SYS_InfoElements where CHARINDEX(',{0},',','+EIC_AllParentID+',')>0 and EIC_Type=12 and EIC_ID<>'{0}' order by EIC_SerialNumb asc ", ccID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            var obj = db.ExecuteDataSet(oCmd);
            if (obj != null && obj.Tables.Count > 0)
            {
                return obj.Tables[0];
            }
            return new DataTable();
        }

        /// <summary>
        /// 将字符串转换为XML格式字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string FormatXML(string str)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(str);
            StringBuilder strbu = new StringBuilder();
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(strbu);
            System.Xml.XmlTextWriter xmlWriter = new System.Xml.XmlTextWriter(stringWriter);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            doc.WriteTo(xmlWriter);
            return strbu.ToString();
        }


        /// <summary>
        /// 获取节点的下级所有子节点
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public DataTable GetInfoElementsNodes(string ccID)
        {
            Database db = DatabaseFactory.CreateDatabase(DbName);
            string sql = string.Format(@" select * from SYS_InfoElements where CHARINDEX(',{0},',','+EIC_AllParentID+',')>0 ", ccID);
            DbCommand oCmd = db.GetSqlStringCommand(sql.ToString());
            DataSet table = db.ExecuteDataSet(oCmd);
            if (table != null && table.Tables[0] != null && table.Tables[0].Rows.Count > 0)
            {
                return table.Tables[0];
            }
            else
            {
                return new DataTable();
            }
        }



        /// <summary>
        /// 获得批量数据列表
        /// </summary>
        /// <param name="parentId">父节点</param>
        /// <param name="ccNodeTypes">节点类型列表</param>
        /// <param name="isHasParentId">查询结果是否包括父节点（默认包括）</param>
        /// <returns></returns>
        public DataTable GetInfoElementsBatchSource(string parentId, IList<string> ccNodeTypes, bool isHasParentId = true)
        {
            StringBuilder strSql = new StringBuilder();
            if (isHasParentId)
            {
                strSql.Append(string.Format(@"  select * from  dbo.SYS_InfoElements  where CHARINDEX(',{0},',','+EIC_AllParentID+',')>0 and EIC_Type in ({1}) ", parentId, ccNodeTypes.ListToStringBySign(",", "'")));
            }
            Database oBase = DatabaseFactory.CreateDatabase("JudgeDoc");
            DbCommand oCmd = oBase.GetSqlStringCommand(strSql.ToString());

            DataTable OtB = oBase.ExecuteDataSet(oCmd).Tables[0];
            if (OtB.Rows.Count > 0)
            {
                return OtB;
            }
            else
            {
                return new DataTable();
            }

        }
        
    }
}
